package com.cold.demo.template.exh;

import com.cold.demo.template.pojo.Res;
import com.cold.demo.template.pojo.StatusCode;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

/**
 * 文件上传超过限制的异常处理器
 */
@RestControllerAdvice
public class MultipartExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(MultipartExceptionHandler.class);

    private MultipartProperties multipartProperties;

    public MultipartExceptionHandler(MultipartProperties multipartProperties) {
        this.multipartProperties = multipartProperties;
    }

    @ExceptionHandler(value = {MultipartException.class})
    public Object handlerMultipartException(MultipartException e) {
        e.printStackTrace();
        Throwable cause = e.getCause().getCause();
        Res       res   = null;
        String    errorMsg;
        if (cause instanceof FileSizeLimitExceededException) {
            errorMsg = String.format("文件大小超过限制，单个上传文件大小不能超过%dMB", multipartProperties.getMaxFileSize().toMegabytes());
            res = Res.error(StatusCode.INPUT_STREAM_TOO_MUCH.getCode(), errorMsg);
        } else if (cause instanceof SizeLimitExceededException) {
            errorMsg = String.format("文件大小超过限制，上传文件总大小不能超过%dMB", multipartProperties.getMaxFileSize().toMegabytes());
            res = Res.error(StatusCode.INPUT_STREAM_TOO_MUCH.getCode(), errorMsg);
        } else {
            errorMsg = e.getMessage();
        }

        if (log.isErrorEnabled()) {
            log.error(errorMsg, e);
        }
        return res != null ? res : Res.error(StatusCode.ERROR.getCode(), "文件上传异常");
    }
}
